# -*- coding: utf-8 -*-
# created on 2016/11/30

from mathsolver.functions.base import *


class GongChaValueUpdate001(BaseFunction):
    """
    等差数列{a_{n}}的公差为2,若a_{2},a_{4},a_{8}成等比数列,则{a_{n}}的前n项和S_{n}=()
    """
    def solver(self, *args):
        assert len(args) == 2
        assert isinstance(args[0], BaseSequence)
        sl = self.search(args[0].name)
        value = args[1].sympify()
        sl.dValue = value
        self.output.append(sl)
        return self


class GongChaValueUpdate002(BaseFunction):
    """
    已知数列{a_{n}}为等差数列,且公差为d.若a_{15}=8,a_{60}=20,求a_{105}的值.
    """
    def solver(self, *args):
        assert len(args) == 1
        assert isinstance(args[0], (BaseVariable, BaseNumber))
        value = args[0].sympify()
        sls = [self.known[item] for item in self.known if isinstance(self.known[item], BaseShuLieDengCha)]
        assert len(sls) == 1
        sl = sls[0]
        sl.dValue = value
        return self


class GongChaValueUpdate003(BaseFunction):
    """
    设{a_{n}}为等差数列,公差d=-2,S_{n}为其前n项和,若S_{10}=S_{11},则a_{1}=.
    """
    def solver(self, *args):
        assert len(args) == 1
        assert isinstance(args[0], BaseEq)
        eq = args[0].sympify()
        sls = [self.known[item] for item in self.known if isinstance(self.known[item], BaseShuLieDengCha)]
        assert len(sls) == 1
        sls = sls[0]
        expr = eq[0] - eq[1]
        symbols = list(expr.free_symbols)
        assert len(symbols) == 1
        sym = symbols[0]
        ans = solve(expr, sym)
        sls.dValue = ans[0]
        return self


class GongChaValueUpdate004(BaseFunction):
    """
    设S_{n}为等差数列{a_{n}}的前n项和,若a_{1}=1,公差d=2,S_{k+2}-S_{k}=24,则k=()
    """
    def solver(self, *args):
        assert len(args) == 1
        assert isinstance(args[0], (BaseEqs, BaseSeqEqs))
        eqs = args[0].sympify()
        sls = [self.known[item] for item in self.known if isinstance(self.known[item], BaseShuLieDengCha)]
        assert len(sls) == 1
        sl = sls[0]
        sl.dValue = eqs[0][1]
        self.known["Sequations"].append(eqs[1])
        return self


class GongChaValueUpdate(BaseFunction):
    CLS = [GongChaValueUpdate001, GongChaValueUpdate002, GongChaValueUpdate003, GongChaValueUpdate004]

    def solver(self, *args):
        r = None
        for cl in GongChaValueUpdate.CLS:
            try:
                r = cl(known=self.known, verbose=True).solver(*args)
                break
            except Exception:
                pass
        if not r:
            raise 'try fail'
        return r
